package com.neo.tiny.business.iot.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neo.tiny.business.iot.entity.BusinessIotDeviceDO;
import com.neo.tiny.business.iot.enums.RelaySwitchStatus;
import com.neo.tiny.business.iot.service.BusinessIotDeviceService;
import com.neo.tiny.business.iot.vo.BusinessIotDevicePageReqVO;
import com.neo.tiny.business.iot.vo.BusinessIotDeviceResVO;
import com.neo.tiny.business.iot.vo.BusinessIotDeviceUpdateReqVO;
import com.neo.tiny.common.common.ResResult;
import com.neo.tiny.middle.socket.api.SocketSessionClient;
import com.neo.tiny.middle.socket.dto.IClientInfo;
import com.neo.tiny.middle.socket.dto.IotWebsocketClientInfo;
import com.neo.tiny.middle.socket.enums.WebSocketType;
import com.neo.tiny.query.LambdaQueryWrapperBase;
import com.neo.tiny.resolver.CommonPage;
import com.neo.tiny.util.MyBatisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: IoT设备管理
 * @Author: yqz
 * @CreateDate: 2023-01-15 01:40:46
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/iot/business-iot-device")
@Api(tags = "IoT设备管理管理")
public class BusinessIotDeviceController {

    private final BusinessIotDeviceService businessIotDeviceService;

    private final List<SocketSessionClient<String>> socketSessionClients;

    /**
     * 分页查询
     *
     * @param req IoT设备管理
     * @return
     */
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public ResResult<Page<BusinessIotDeviceResVO>> getBusinessIotDevicePage(@Valid BusinessIotDevicePageReqVO req) {

        Page<BusinessIotDeviceDO> page = businessIotDeviceService.page(MyBatisUtils.buildPage(req), new LambdaQueryWrapperBase<BusinessIotDeviceDO>()
                .likeIfPresent(BusinessIotDeviceDO::getDeviceName, req.getDeviceName()));

        SocketSessionClient<String> socketSessionClient = socketSessionClients
                .stream()
                .filter(client -> client.support(WebSocketType.IOT.getType()))
                .findFirst().get();

        List<IClientInfo> websocketClientInfos = socketSessionClient.listAllSession();

        Map<String, IotWebsocketClientInfo> clientInfoMap = websocketClientInfos.stream()
                .map(clientInfo -> (IotWebsocketClientInfo) clientInfo)
                .collect(Collectors.toMap(IotWebsocketClientInfo::getClientId, Function.identity(), (e1, e2) -> e1));

        Page<BusinessIotDeviceResVO> res = CommonPage.restPage(page, BusinessIotDeviceResVO.class);


        res.getRecords().forEach(device -> {
            IotWebsocketClientInfo clientInfo = clientInfoMap.get(device.getDeviceId());

            device.setOnlineStatus(BeanUtil.isNotEmpty(clientInfo) ? 1 : 0);

            device.setSwitchStatus(BeanUtil.isNotEmpty(clientInfo) ? clientInfo.getSwitchStatus() : RelaySwitchStatus.OFF.getAction());
        });

        return ResResult.success(res);
    }


    /**
     * 修改IoT设备管理
     *
     * @param businessIotDeviceUpdateReqVO IoT设备管理
     * @return ResResult
     */
    @ApiOperation("修改IoT设备管理")
    @PutMapping("/update")
    public ResResult<Boolean> updateById(@Valid @RequestBody BusinessIotDeviceUpdateReqVO businessIotDeviceUpdateReqVO) {
        businessIotDeviceService.updateById(BeanUtil.copyProperties(businessIotDeviceUpdateReqVO, BusinessIotDeviceDO.class));
        return ResResult.success(true);
    }

    /**
     * 通过id删除IoT设备管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation("通过id删除IoT设备管理")
    @DeleteMapping("/{id}")
    public ResResult<Boolean> removeById(@PathVariable Integer id) {
        return ResResult.success(businessIotDeviceService.removeById(id));
    }

}
